<?php
/**
 * 字母+数字的验证码生成
 */
// 开启session
session_start();
//1.创建黑色画布
$image = imagecreatetruecolor(200, 60);
  
//2.为画布定义(背景)颜色
$bgcolor = imagecolorallocate($image, 255, 255, 255);
  
//3.填充颜色
imagefill($image, 0, 0, $bgcolor);
  
// 4.设置验证码内容
  
//4.1 定义验证码的内容
$content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz234567890";
  
//4.1 创建一个变量存储产生的验证码数据，便于用户提交核对
$captcha = "";
for ($i = 0; $i < 4; $i++) {
    // 字体大小
    $fontsize = 25;
    $angle = mt_rand(-15,+15);
    $font = 'consolab.ttf';
    // 字体颜色
    $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
    // 设置字体内容
    $fontcontent = substr($content, mt_rand(0, strlen($content)-1), 1);
    $captcha .= $fontcontent;
    // 显示的坐标
    $x = ($i * 200 / 4) + mt_rand(10, 20);
    $y = 30 + mt_rand(0, 20);
    // 填充内容到画布中
    imagettftext($image, $fontsize, $angle, $x, $y, $fontcolor, $font, $fontcontent);
}
$_SESSION["captchaimg"] = $captcha;
  
//4.3 设置背景干扰元素
for ($$i = 0; $i < 300; $i++) {
    $pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
    $circle_dia = mt_rand(1,3);
    imagefilledarc($image, mt_rand(1,199), mt_rand(1,59), $circle_dia, $circle_dia, 0, 360, $pointcolor, IMG_ARC_PIE);
    #imagesetpixel($image, mt_rand(1, 199), mt_rand(1, 59), $pointcolor);
}
  
//4.4 设置干扰线
for ($i = 0; $i < 7; $i++) {
    $linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
    imagesetthickness($image, $i+1-(int)($i/2)*2);
    imageline($image, mt_rand(1, 199), mt_rand(1, 59), mt_rand(1, 199), mt_rand(1, 59), $linecolor);
    /*$start_x = mt_rand(1,199);
    $start_y = mt_rand(1,59);
    $end_x = mt_rand(1,199);
    $end_y = mt_rand(1,59);
    $line_width = mt_rand(1,3);
    $polygen_arr = array(
        $start_x, $start_y,
        $start_x+$line_width, $start_y+$line_width,
        $end_x, $end_y,
        $end_x+$line_width, $end_y+$line_width,
    );
    imagefilledpolygon($image,$polygen_arr, 4, $linecolor);*/
}
  
//5.向浏览器输出图片头信息
header('content-type:image/png');
  
//6.输出图片到浏览器
imagepng($image);
  
//7.销毁图片
imagedestroy($image);
